﻿using System;
using System.Collections.Concurrent;
using NLog;

namespace Ast.Framework.Logging
{
    /// <summary>
    /// The purpose of the queue is to be used in FastRichTextBoxTarget for queuing logging messages
    /// </summary>
    public interface ILoggingMessageQueue
    {
        bool IsEmpty();
        void Enqueue(LogEventInfo logEventInfo);
        void Enqueue(int levelOrdinal, string loggerName, string message);
        LogEventInfo Dequeue();
        void Clear();
    }

    public class DefaultLoggingMessageQueue : MarshalByRefObject, ILoggingMessageQueue
    {
        private ConcurrentQueue<LogEventInfo> _msgQueue;

        private readonly object _syncRoot = new object();

        public DefaultLoggingMessageQueue()
        {
            _msgQueue = new ConcurrentQueue<LogEventInfo>();
        }

        public bool IsEmpty()
        {
            return _msgQueue.IsEmpty;
        }

        public void Enqueue(LogEventInfo logEventInfo)
        {
            _msgQueue.Enqueue(logEventInfo);
        }

        public void Enqueue(int levelOrdinal, string loggerName, string message)
        {
            _msgQueue.Enqueue(new LogEventInfo(LogLevel.FromOrdinal(levelOrdinal), loggerName, message));
        }

        public LogEventInfo Dequeue()
        {
            LogEventInfo logEventInfo;
            _msgQueue.TryDequeue(out logEventInfo);
            return logEventInfo;
        }

        public void Clear()
        {
            lock (_syncRoot)
            {
                _msgQueue = new ConcurrentQueue<LogEventInfo>();
            }
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}